package com.bruce.tool.map.baidu.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bruce.tool.map.baidu.web.config.BaiduConfig;
import com.bruce.tool.map.baidu.web.constant.MapApiConstant;
import com.bruce.tool.map.baidu.web.to.*;
import com.bruce.tool.rpc.http.core.Https;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 百度地图转换
 *
 * @author Bruce(刘正航)
 */
@Component
public class AddressTranslateHandler {

    @Autowired
    private BaiduConfig baiduConfig;

    public Point translate(String address) {
        String resultInfo = Https.create().url(MapApiConstant.ADDRESS_TO_POINT_URL)
                .add("address", address)
                .add("output", "json")
                .add("ak", baiduConfig.getAk())
                .get();
        MapResult result = JSON.parseObject(resultInfo, MapResult.class);
        if (Objects.isNull(result) || Objects.isNull(result.getResult())) {
            return null;
        }
        return result.getResult().getLocation();
    }

    public Address translate(Point point) {
        String resultInfo = Https.create().url(MapApiConstant.POINT_TO_ADDRESS_URL)
                .add("location", point.toLocation())
                .add("coordtype", "wgs84ll")
                .add("output", "json")
                .add("ak", baiduConfig.getAk())
                .get();
        BaseMapResult<ReverseAddress> result = JSON.parseObject(resultInfo, new TypeReference<BaseMapResult<ReverseAddress>>() {
        });
        if (Objects.isNull(result) || Objects.isNull(result.getResult())) {
            return null;
        }
        return result.getResult().toAddress();
    }
}
